package com.dkm.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.dkm.repository.StudentRepository;
import com.dkm.repository.TraceRepository;
import com.dkm.repository.UsersRepository;
import com.dkm.entity.Student;
import com.dkm.entity.Trace;
import com.dkm.entity.Users;
import com.dkm.service.TraceService;
import com.dkm.util.ResultUtil;

@Service
public class TraceServiceImpl implements TraceService {

	//注入跟踪持久层
	@Autowired
	private TraceRepository TraceRepository;
	//注入用户持久层
	@Autowired
	private UsersRepository usersRepository;
	//注入学生持久层
	@Autowired
	private StudentRepository studentRepository;
	
	@Override
	public Page<Trace> findAllTraces(Map<String, Object> map, Pageable pageable) {
		
		return TraceRepository.findAll(this.get(map), pageable);
	}
	

	private Specification<Trace> get(Map<String, Object> map) {
		return new Specification<Trace>() {
			@Override
			public Predicate toPredicate(Root<Trace> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				//1创建Predicate对象，动态sql表达式
				Predicate predicate=criteriaBuilder.conjunction();
				//2创建一个集合存放多个条件，动态sql表达式集合
				List<Expression<Boolean>> expressions=predicate.getExpressions();
				//学生编号
				if(!StringUtils.isEmpty(map.get("sid"))) {
					expressions.add(criteriaBuilder.equal(root.get("student").get("sid"), map.get("sid")));
				}
				return predicate;
			}
		};
	}


	@Transactional //开启事务
	@Override
	public ResultUtil addTrace(String user_id,String sid,Trace trace) {
		if(user_id!=null) {
			//根据id获取用户信息
			Users user=usersRepository.findById(user_id).get();
			//设置用户信息
			trace.setUser(user);
		}
		if(sid!=null) {
			//根据id获取学生信息
			Student student=studentRepository.findById(sid).get();
			//设置学生信息
			trace.setStudent(student);
		}
		
		//生成id和设置创建时间
		trace.setTrace_id(UUID.randomUUID().toString());
		trace.setCreate_time(new Date());
		
		//执行添加
		Trace t=TraceRepository.saveAndFlush(trace);
		if(t!=null) {
			//创建定时任务
			
			
			return new ResultUtil(0, "添加成功", t);
			
		}
		return new ResultUtil(-1, "添加失败", null);
	}

}
